#include "ina226.h"

#define INA226_ADDR 0x40

#define Config_Reg 0x00
#define Shunt_V_Reg 0x01
#define Bus_V_Reg 0x02
#define Power_Reg 0x03
#define Current_Reg 0x04
#define Calib_Reg 0x05
#define Mask_En_Reg 0x06
#define Alert_Reg 0x07
#define Man_ID_Reg 0xFE // 0x5449
#define ID_Reg 0xFF     // 0x2260

// const uint8_t INA226_CONFIG[2] = {0x48, 0x4F}; // 芯片配置
const uint8_t INA226_CONFIG[2] = {0x45, 0x27}; // 芯片配置
const uint8_t CALIB_CTRL[2] = {0x01, 0xA3};    // 校准命令

float result = 0;

ina226_infor_t ina226_infor = {0};

void ina226_init(void)
{
    bsp_iic_sw_send_data(INA226_ADDR, Config_Reg, (uint8_t *)INA226_CONFIG, 2);
    bsp_iic_sw_send_data(INA226_ADDR, Calib_Reg, (uint8_t *)CALIB_CTRL, 2);
    delay_ms(10);

    // bsp_iic_sw_rece_data(INA226_ADDR, Man_ID_Reg, &ina226_infor.read_buf);
    // printf("ID = %x \n", ina226_infor.read_buf);
}

void ina226_operation(void)
{
    switch (nt3_infor.display_type)
    {
    case DISP_VOLTAGE:
        bsp_iic_sw_rece_data(INA226_ADDR, Bus_V_Reg, &ina226_infor.read_buf);
        ina226_infor.votlage = ina226_infor.read_buf * 1.25;
        ina226_infor.votlage = ina226_infor.votlage / 1000;

        nixie_tube_num_update(ina226_infor.votlage);
        printf("V = %.6f \t", ina226_infor.votlage);
        break;

    case DISP_ELECTRICITY:
        bsp_iic_sw_rece_data(INA226_ADDR, Current_Reg, &ina226_infor.read_buf);
        ina226_infor.electricity = ina226_infor.read_buf * 0.000061098;

        nixie_tube_num_update(ina226_infor.electricity);
        printf("A = %.6f \n", ina226_infor.electricity);
        break;

    case DISP_VOLTAGE_POWER:
        bsp_iic_sw_rece_data(INA226_ADDR, Power_Reg, &ina226_infor.read_buf);
        ina226_infor.power = ina226_infor.read_buf * 25 * 0.000061098;

        nixie_tube_num_update(ina226_infor.power);
        printf("INA226:P = %.6f \t", ina226_infor.power);
        break;

    default:
        printf("ina226_operation state error !\n");
        break;
    }
}
